package com.itrip.repository.impl;

import com.itrip.document.Hotel;
import com.itrip.repository.HotelRepository;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Repository
public class HotelRepositoryImpl implements HotelRepository {
    @Resource
    private SolrClient solrClient;
    @Override
    public List<Hotel> getHotelByQuery(String keyword, Integer start, Integer pageSize) throws IOException, SolrServerException {
        SolrQuery solrQuery = new SolrQuery();
        if (!StringUtils.isEmpty(keyword)){

            solrQuery.setQuery("hotelName:"+keyword+" or address:"+keyword);
        }else {
            solrQuery.setQuery("*:*");
        }
        solrQuery.setStart(start);
        solrQuery.setRows(pageSize);
        solrQuery.addHighlightField("hotelName");
        solrQuery.addHighlightField("address");
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        QueryResponse queryResponse = solrClient.query("hotel", solrQuery);
        List<Hotel> hotelList = queryResponse.getBeans(Hotel.class);
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        for (Hotel hotel : hotelList) {
            List<String> hotelName = highlighting.get(hotel.getId()).get("hotelName");
            if (hotelName != null && hotelName.size() > 0){
                hotel.setHotelName(hotelName.get(0));
            }
            List<String> address = highlighting.get(hotel.getId()).get("address");
            if (address != null && address.size() > 0){
                hotel.setAddress(address.get(0));
            }
        }
        return hotelList;
    }

    @Override
    public Long getHotelCount(String keyword) throws IOException, SolrServerException {
        SolrQuery solrQuery = new SolrQuery();
        if (!StringUtils.isEmpty(keyword)){

            solrQuery.setQuery("hotelName:"+keyword+" or address:"+keyword);
        }else {
            solrQuery.setQuery("*:*");
        }
        QueryResponse queryResponse = solrClient.query("hotel", solrQuery);

        return  queryResponse.getResults().getNumFound();
    }
}
